<template>
  <div style="width: 100%">
    <div style="display: flex; width: 100%">
      <div class="mr-2" style="width: 100%">
        <el-popover
          v-if="onlyImage || tempImage"
          placement="top"
          trigger="hover"
        >
          <el-image
            style="width: 100%; height: auto"
            :src="tempImage"
          ></el-image>
          <template #reference>
            <el-input
              style="width: 100%"
              v-model="tempImage"
              clearable
              :placeholder="
                !placeholder ? $t('common.message.upload.input') : placeholder
              "
            ></el-input>
          </template>
        </el-popover>
        <el-input
          v-else
          style="width: 100%"
          v-model="tempImage"
          clearable
          :placeholder="
            !placeholder ? $t('common.message.upload.input') : placeholder
          "
        ></el-input>
      </div>
      <div>
        <div style="display: flex; align-items: center">
          <el-button type="success" icon="Grid" @click="openImagesPick">
            {{ $t('common.title.select') }}
          </el-button>
          <div style="margin-left: 5px">
            <el-upload
              v-loading="loading"
              action="#"
              ref="uploadRef"
              class="image-uploader"
              :http-request="handleUpload"
              :show-file-list="false"
              :before-upload="handleBeforeUpload"
              :on-exceed="handleOnExceed"
              :multiple="false"
              :limit="1"
            >
              <template #trigger>
                <el-button type="primary" icon="Upload">
                  {{ $t('common.action.upload') }}
                </el-button>
              </template>
            </el-upload>
          </div>
        </div>
      </div>
    </div>
    <ra-file-picker
      ref="refFilePicker"
      :multiple="false"
      :onlyImage="onlyImage"
      @update="updateSelect"
    />
  </div>
</template>

<script setup>
/**
 * 单文件上传,带输入框，可直接粘贴URL
 */
import { smartTranslate as $t } from '@/lang';
import AdminFileAPI from '@/api/admin/admin/file';

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  onlyImage: {
    type: Boolean,
    default: false,
  },
  placeholder: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['update:modelValue']);
const uploadRef = ref();
const tempImage = ref(props.modelValue);
const loading = ref(false);

watch(
  () => props.modelValue,
  (newVal) => {
    tempImage.value = newVal;
  },
  { immediate: true },
);

const handleUpload = (options) => {
  loading.value = true;
  AdminFileAPI.add(options.file)
    .then(({ data }) => {
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.upload'),
        }),
      );
      tempImage.value = data;
      emit('update:modelValue', tempImage.value.url);
    })
    .catch(() => {
      ElMessage.error(
        $t('common.message.failed.general', {
          action: $t('common.action.upload'),
        }),
      );
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleOnExceed = (files) => {
  tempImage.value = '';
  handleUpload({ file: files[0] });
};

const handleBeforeUpload = (event) => {
  if (props.onlyImage && event.type.split('/')[0] != 'image') {
    ElMessage.error($t('common.message.info.only_image'));
    return false;
  }
};

// 图片选择
const refFilePicker = ref();
const openImagesPick = () => {
  refFilePicker.value.show();
};
const updateSelect = (data) => {
  const urlList = data.map((file) => file.url);
  emit('update:modelValue', urlList[0]);
};
</script>

<style lang="scss" scoped></style>
